<template>
	<view class="page-bg">
		<view class="answer">
			<view class="margin-bottom36" style="padding-top:157upx;">
				<!-- 题目 -->
				<view v-if="index == answerIndex" v-for="(value, index) in list" :key="index">
					<!-- top -->
					<view class="margin-left36 margin-right36 flex margin-bottom89 padding-left30 padding-right30 bg-color-white border-radius10" style="height:146upx">
						<view class="left dis-flex "><image class="width90 height90 border-radius" :src="_userInfo.avatarUrl || _gameInfo.photo"></image></view>
						<view class="content dis-flex margin-left28">
							<view class="bg-back-w">
								<view class="font-siez30">{{ _userInfo.nickName || _gameInfo.nickName }}</view>
								<view class="font-size26" style="color:#949494">
									已经连续答对
									<text class="color-red">{{ answerIndex + 1 }}</text>
									/{{ list.length }} 题
								</view>
							</view>
						</view>
						<view class="right dis-flex flex-column margin-left28 text-center">
							<view class="font-size26 mb10" style="color: #ffca3e;">难易度</view>
							<uni-rate :value="index / 4 + 1" size="12" disabled="true"></uni-rate>
						</view>
					</view>
					<view class="margin-left36 margin-right36 pr padding-top97 bg-color-white border-radius10" style="width:680upx;min-height:850upx">
						<view class="mCe top-48 tranformZ" style="width:453upx;height:117upx;">
							<image class="bg-back" src="/static/images/ui_dati_01.png"></image>
							<view class="mCe top18 text-center color-white font-size36">第&nbsp;{{ index + 1 }}&nbsp;题</view>
						</view>
						<view class="dis-flex margin-bottom35">
							<view style="width:90px;height:90px">
								<view v-if="downTimeState" class="scale-up-center">
									<circle-count-down :size="45" :total="value.downTime" @callback="downCallback"></circle-count-down>
								</view>
							</view>
						</view>
						<view class="dis-flex">
							<view style="width:557upx">
								<view class="animated fadeInRight">
									<view class="font-size26 color-block margin-bottom50">{{ value.answerTitle }}</view>
									<view class="margin-auto" style="width:514upx">
										<view v-for="(v, i) in value.answerLists" :key="i">
											<!-- 未选择 -->
											<view
												v-if="v.result == 1"
												@click="btnOptionAnswer({ value: value, index: index, v: v, i: i })"
												class="pr height78 dis-flex border-radius margin-bottom34"
												style="background-color:#EDEEF3"
											>
												<text class="font-size24 color-block">{{ answerTiTles[i] }}.{{ v.answer }}</text>
											</view>
											<!-- 正确 -->
											<view v-if="v.result == 2" class="pr height78 dis-flex border-radius margin-bottom34" :style="'background-color:' + bgcolor">
												<text class="font-size24 color-white">{{ answerTiTles[i] }}.{{ v.answer }}</text>
												<image class="vCe right34 width30 height30" src="/static/images/ui_gou.png"></image>
											</view>
											<!-- 错误 -->
											<view v-if="v.result == 3" class="pr height78 dis-flex border-radius margin-bottom34" style="background-color:#FF626D">
												<text class="font-size24 color-white">{{ answerTiTles[i] }}.{{ v.answer }}</text>
												<image class="vCe right34 width30 height30" src="/static/images/ui_cha.png"></image>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="margin-top36 margin-bottom36"><banner-ad></banner-ad></view>
				</view>
			</view>
		</view>
		<c-pop></c-pop>
	</view>
</template>
<script>
let list = [
	{
		id: 308,
		answerTitle: '【抵抗之靴】的韧性效果对东皇太一的大招有效吗?',
		status: 1,
		userId: 0,
		createTime: 1569817069000,
		downTime: 6,
		isLast: 0, // 是否最后一题  0 否 1是
		isPlayVideo: 0, // 是否播放广告  0 否 1是
		answerLists: [
			{
				answerTiTle: 'A',
				answer: '无效',
				result: 1 // 1未选中  2正确  3错误
			},
			{
				answerTiTle: 'B',
				answer: '有效',
				result: 1 // 1未选中  2正确  3错误
			}
		]
	}
];

import CryptoJS from 'crypto-js';
import CircleCountDown from '@/components/circle-count-down';
import { uniRate } from '@dcloudio/uni-ui';
import { mapGetters, mapActions } from 'vuex';
import { clearTimeout } from 'timers';
export default {
	name: 'answer',
	props: {},
	components: {
		uniRate,
		CircleCountDown
	},
	data() {
		return {
			list: [],
			downTimeState: true,
			downTime: 12, // 12
			answerIndex: 0, // 第几题目
			resetNum: 1, // 复活次数
			resurrectedNum: 0, // 已复活次数
			isStepTwo: false, //是否为第二流程
			isClickBannerAd:false,//是否点击了bannerAd
			answerTiTles: ['A', 'B', 'C', 'D', 'E', 'F'],

			bgcolor: '#1AC97C',
		};
	},
	watch: {},
	computed: {
		...mapGetters('user', ['_userInfo', '_gameInfo']),
		...mapGetters('pop', ['_pop']),
		isShowShare: function() {
			return this.resetNum == 0 && !this.isStepTwo;
		}
	},
	methods: {
		...mapActions('pop', ['popShow']),
		...mapActions('user', ['gameInfoUp']),
		//获取深色模块
		getRandomColor() {
			let color = '#';
			const r = this.$util.joinZeroNum(Math.floor(Math.random() * 255).toString(16));
			const g = this.$util.joinZeroNum(Math.floor(Math.random() * 200).toString(16));
			const b = this.$util.joinZeroNum(Math.floor(Math.random() * 255).toString(16));
			color += r + g + b;
			console.log(color);
			return color;
		},
		// 选择答案
		async btnOptionAnswer(obj) {
			if (obj.index >= (this.list.length / 4) * 3 && this.isStepTwo) {
				this.resetNum = 0; //第二流程且已过3/4进程的不予以复活
			}
			this.downTimeState = false;
			this.list[obj.index].answerLists.forEach(item => {
				item.result = 1;
			});
			let qaResult = await this.answerResult({
				answerId: obj.value.id,
				answerResult: obj.v.answerTiTle,
				isLast: obj.value.isLast
			});
			this.list[obj.index].answerLists[obj.i].result = qaResult ? 2 : 3;
			this.bgcolor = this.getRandomColor();
			setTimeout(() => {
				if (qaResult) {
					if (obj.value.isLast == 0) {
						this.answerIndex++;
						this.downTimeState = true;
					} else {
						this.popShow('CQaSuccess');
					}
				} else {
					this.resetNum--;
					this.downTimeState = false;
					if (this.resetNum >= 0) {
						this.resurrectedNum++;
						this.popShow({
							key: 'CCountRebirth',
							value: {
								isStepTwo: this.isStepTwo,
								isShowShare: this.isShowShare,
								resurrectedNum: this.resurrectedNum
							}
						});
					} else {
						this.popShow('CQaError');
					}
				}
			}, 500);
		},

		// 倒计时 回调
		downCallback(val) {
			if (this.downTimeState) {
				this.resetNum--;
				this.downTimeState = false;
				if (this.resetNum >= 0) {
					this.resurrectedNum++;
					this.popShow({
						key: 'CCountRebirth',
						value: {
							isStepTwo: this.isStepTwo,
							isShowShare: this.isShowShare,
							resurrectedNum: this.resurrectedNum
						}
					});
				} else {
					this.popShow('CQaError');
				}
			}
		},
		async answerBankList() {
			try {
				let res = await this.$api.home.answerBankList();
				let list = res.data;
				this.isStepTwo = res.isStepTwo == 1 ? true : false;
				if (!this.isStepTwo) {
					this.resetNum = list.length / 4; //第一流程用户三次复活
				}
				this.list = list.map((value, index) => {
					value.downTime = value.downTime || this.downTime; // 倒计时
					value.isLast = 0; // 是否最后一题

					if (index == list.length - 1) {
						value.isLast = 1; // 是否最后一题
					}
					value.isPlayVideo = 0; //是否要播放广告视频
					if (index % 5 == 4) {
						value.isPlayVideo = 1;
					}

					const answerTitle = value.answerTitle;
					var parsedWordArray = CryptoJS.enc.Base64.parse(answerTitle);
					value.answerTitle = parsedWordArray.toString(CryptoJS.enc.Utf8);
					console.log('parsed:', value.answerTitle);

					const newArr = [];
					for (let i = 0, len = value.answerLists.length; i < len; ) {
						i++;
						let currentRandom = parseInt(Math.random() * len);
						if (!newArr.includes(value.answerLists[currentRandom])) {
							value.answerLists[currentRandom].result = 1; // 1未选中  2正确  3错误s
							newArr.push(value.answerLists[currentRandom]);
						} else {
							i--;
						}
					}
					value.answerLists = newArr;
					return value;
				});
				console.log(this.list);
				this.gameInfoUp();
			} catch (e) {
				//TODO handle the exception
				console.log(e);
				uni.navigateBack();
			}
		},
		async answerResult(obj) {
			if (obj.isLast == 1) {
				this.downTimeState = false;
			}
			let res = await this.$api.home.answerResult({
				answerId: obj.answerId, // 题目ID
				answerResult: obj.answerResult, // 答案 id
				isLast: obj.isLast // 是否最后一题  0否 1是
			});
			console.log(res === 0 || res === 1);
			return res === 0 || res === 1;
		},
		popClose() {
			this.list.forEach((value, index) => {
				if (this.answerIndex == index) {
					value.downTime = this.downTime; // 倒计时
					value.answerLists.map((v, i) => {
						v.result = 1; // 1未选中  2正确  3错误s
					});
				}
			});
			this.downTimeState = true;
		},
		init() {
			this.downTime = 12;
			this.answerIndex = 0;
			this.resetNum = 1;
			this.resurrectedNum = 0;
			this.downTimeState = true;
		},
		//从APP那边监控app.hide事件，判断是否是点击了banner广告触发的
		clickBannerAdHide() {
			console.log('this._pop.CCountRebirth', this._pop.CCountRebirth);
			console.log('this.isStepTwo', this.isStepTwo);
			// 点击了广告复活
			if (this._pop.CCountRebirth && !this.isStepTwo && this.resurrectedNum > 1) {
				this.isClickBannerAd = true
				this.popShow();
			}
		},
		//从APP那边监控app.show事件，判断是否是点击了banner广告触发后返回了
		clickBannerAdShow() {
			console.log('this.isClickBannerAd', this.isClickBannerAd);
			// 点击了广告复活
			if (this.isClickBannerAd) {
				this.popClose();
				this.isClickBannerAd = false
			}
		}
	},
	created() {
		this.$bus.on('popClose', val => {
			this.popClose();
		});
		this.$bus.on('AppHide', val => {
			console.log('bus AppHide')
			this.clickBannerAdHide();
		});
		this.$bus.on('AppShow', val => {
			console.log('bus AppShow')
			this.clickBannerAdShow();
		});
	},
	async mounted() {
		this.init();
		if (!this._gameInfo) {
			this.gameInfoUp();
		}
		this.answerBankList();
	},
	onShareAppMessage(res) {
		const num = Math.floor(Math.random() * 6 + 1);
		console.log('onShareAppMessage', res);
		if (res.from === 'button') {
			// 来自页面内分享按钮
			if (res.target.id == 'rebirth') {
				this.popShow();
			}
		}
		return {
			title: '答题赢Q币和荣耀皮肤，几率极高，快来试试',
			path: '/pages/tabBar/home/index?shareUserId=' + this._gameInfo.userId,
			imageUrl: 'https://miaozhua-test.oss-cn-hangzhou.aliyuncs.com/luckKing/icon/share' + num + '.jpg',
			success: () => {
				if (res.target.id == 'rebirth') {
					this.$tip.showToast('分享成功', 'none');
					setTimeout(() => {
						this.popClose();
					}, 1000);
				}
			},
			fail: () => {
				if (res.target.id == 'rebirth') {
					this.popShow({
						key: 'CCountRebirth',
						value: {
							isStepTwo: this.isStepTwo,
							isShowShare: this.isShowShare,
							resurrectedNum: this.resurrectedNum
						}
					});
					this.$tip.showToast('分享失败', 'none');
				}
			}
		};
	}
};
</script>
<style lang="scss" scoped>
.answer {
}
</style>
